import React, { useState }  from 'react';  
import { Form, Input, Button, Upload,message,Card,Table,Alert, Checkbox,Row,Col,Popconfirm,List,Modal } from 'antd';  
import { UploadOutlined,DownloadOutlined } from '@ant-design/icons';  
import { useTranslation } from 'react-i18next';  
import { CSSProperties } from 'react';  
import { createReport,editProduct,separatedFm,addFmReact,editFm,separatedFix,separatedCreateReport,subjectTestResult,updateSubjectTestResult,mixedfm,mixedFix,mixedCreateReport,getRmInciResult,saveSafetyRmInciResult,batchSaveRmInciResult,updateDataResult,uploadRemark,uploadRemarkUpdate,delRemark,refreshResult} from "@/api/modules/jhreport";
import '../../report/step/MergedCellsTable.css'// 引入自定义的CSS样式 
import FullscreenLoading from '@/components/FullscreenLoading';
import {uploadData,uploadDataByHand } from "@/api/modules/screening";
import { list} from "@/api/modules/inci";
import {download} from '@/utils/request';
import useCacheAlive from '@/hooks/useCacheAlive';

const FileUpload = ({ formData,tableData, onUploadSuccess }) => {  
  const [form] = Form.useForm();  
  const { t } = useTranslation();  
  const [fileCache,setFilecache] = useCacheAlive({},`table-fmScreening-fileCache`) 
  const [uploading, setUploading] = useState(false);  
  const [fileList, setFileList] = useState([]); 
  const [errMsg,setErrMsg] = useState([]); 
  const [errCode,setErrCode] = useState('');
  const [percentMsg,setPercentMsg] = useState([]);
  const [functionMsg,setFunctionMsg] = useState([]);
  const [inciCnMsg,setInciCnMsg] = useState([]);
  const [rawData,setRawData] = useState([])
  const [showCoverCheckbox, setShowCoverCheckbox] = useState(false);  
  const [fm_isCover1,setIsCover] = useCacheAlive(false,`table-fmScreening-fm_isCover1`) 
  const [fm_isFunction1,setIsFunction] = useState(false) 
  const [showConfirmCheckbox, setShowConfirmCheckbox] = useState(false);  
  const [showErrorTitle, setShowErrorTitle] = useState(false);  
  const [loading, setLoading] = useState(false); 
  const [dataSource, setDataSource] =  useCacheAlive([],`table-fmScreening-dataSource`)

  // 初始设置表单值  
  React.useEffect(() => {  
    console.log(tableData,'tableData')
    if(tableData == undefined || tableData == "" || tableData == null){
    }else{
        formData.fm_name=tableData.fmName
        setRawData(tableData.rawTsData)
    }
    formData.fm_isCover = false
    formData.fm_isFunction = false
    form.setFieldsValue(formData);
    console.log(fileCache,'表单数据') 

  }, [form, formData]);  
  

  

  const columns = [  
    {  
        title: t('report.RMSerial'),  
        dataIndex: '原料序号',  
        key: '原料序号',  
        onCell: (_, index) => {
            const data = getSpanArr(rawData,'原料序号','原料序号')
            return {rowSpan : data[index]};
          }, 
      }, 
      {  
        title: t('report.RMCode'),  
        dataIndex: '原料Code',  
        key: '原料Code',  
        onCell: (_, index) => {
            const data = getSpanArr(rawData,'原料序号','原料Code')
            return {rowSpan : data[index]};
          },   
      }, 
      {  
        title: t('report.RMName'),  
        dataIndex: '原料名',  
        key: '原料名', 
        onCell: (_, index) => {
            const data = getSpanArr(rawData,'原料序号','原料名')
            return {rowSpan : data[index]};
          },   
      }, 
      {  
        title: t('report.INCICN'),  
        dataIndex: '标准中文名称INCI中文',  
        key: '标准中文名称INCI中文',  
      },  
    {  
      title: t('report.INCIEN'),  
      dataIndex: 'INCI名称INCI英文',  
      key: 'INCI名称INCI英文',  
    },  
    {  
      title:  t('report.RMPercentage'),  
      dataIndex: '原料含量%',  
      key: '原料含量%',   
      onCell: (_, index) => {
        const data = getSpanArr(rawData,'原料序号','原料含量%')
        return {rowSpan : data[index]};
      },  
    },  
    {  
        title: t('report.IngredientPercentageinRM'),  
        dataIndex: '原料中成分含量%',  
        key: '原料中成分含量%',  
      }, 
      {  
        title: t('report.Function'),  
        dataIndex: '使用目的',  
        key: '使用目的',  
      },
      {  
        title: t('report.remark'),  
        dataIndex: '备注',  
        key: '备注',  
      },
    // 可以根据需要添加更多列...  
  ];
  
  const getSpanArr =(data,dataIndex,dataIndex2) =>{
    let spanArr=[]
    let pos = 0
    // data就是我们从后台拿到的数据
    for (var i = 0; i < data.length; i++) {
      if (i === 0) {
        spanArr.push(1);
        pos= 0;
      } else {
        // 判断当前对象的指定属性值与上一个对象的指定属性值是否相等
        if (data[i][dataIndex] === data[i - 1][dataIndex] ) {
          if (data[i][dataIndex2] === data[i - 1][dataIndex2] ) {
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            spanArr.push(1);
            pos = i;
          }
        }else{
          spanArr.push(1);
          pos = i;
        }
      }
    }
    return spanArr
  }

  
    const guid =() =>{
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          let r = Math.random() * 16 | 0,
              v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
      });
    }

  const handleSubmit = async () => {  
    try {  
      // 验证表单  
      await form.validateFields();  
      // 假设我们从表单中获取文件和其他字段信息  
      const values = form.getFieldsValue();  
      const { file } = values;  
      setLoading(true)
      let uuid =guid()
      // 构造FormData对象  
      const formData1 = new FormData(); 
      if(fm_isCover1 == true){
      }else{
        const file1 = values.file.originFileObj
        formData1.append("blFile",file1);
      }
      formData1.append("efficacy", formData.efficacy);
      formData1.append("form", formData.form);
      formData1.append("method", formData.method);
      formData1.append("population", formData.population);
      formData1.append("position", formData.position);
      formData1.append("classification", formData.classification);
      formData1.append("nameCn", formData.nameCn);
      formData1.append("nameEn", formData.nameEn);
      if(formData.productCode==undefined || formData.productCode == null || formData.productCode==""){
        formData1.append("productCode", "");
       }else{
        formData1.append("productCode", formData.productCode);
       }
      if(formData.useTimes==undefined || formData.useTimes==null || formData.useTimes==""){
        formData1.append("useTimes", "");
     }else{
      formData1.append("useTimes", formData.useTimes);
     }
     if(formData.bodyWeightKg==undefined || formData.bodyWeightKg==null || formData.bodyWeightKg==""){
      formData1.append("bodyWeightKg", "");
     }else{
      formData1.append("bodyWeightKg", formData.bodyWeightKg);
     }
     formData1.append("key", uuid);
      if(fm_isCover1 == true){
        //勾选，调用手动上传
        console.log("ss")
        let newHand = formData
        newHand.testDefId = 3
        newHand.key = uuid
        newHand.fmCheckInciList = dataSource
        uploadDataByHand(newHand).then(res=>{
          if(res.data.msg == '操作成功'){
            let newTable = res.data.data
            onUploadSuccess('2',newTable)
            setLoading(false)
          }else{
            message.error("Error")
            setLoading(false)
          }
        })
      }else{
        //文件上传
        uploadData(formData1).then(res=>{
          if(res.data.msg == '操作成功'){
            let newTable = res.data.data
            onUploadSuccess('2',newTable)
            setLoading(false)
          }else{
            message.error("Error")
            setLoading(false)
          }
        })
      }
    } catch (error) {  
      console.error('Form submission failed:', error);  
      message.error('表单提交失败，请检查输入内容');  
      setLoading(false)
      // 设置上传状态为false  
      setUploading(false);  
    }  
  };  
    
  const handleFileChange = (info) => { 
    console.log(info,'info') 
    info.file.status = "done"
    form.setFieldsValue({  
        file: info.file,  
      }); 
   setFilecache(info.file)
  };  

  const handleIsCoverCheckboxChange = (e) => {  
    setIsCover(e.target.checked); // 使用 setIsCover 函数来更新状态  
    formData.fm_isCover=e.target.checked
  };  

  const handleIsFunctionCheckboxChange = (e) => {  
    setIsFunction(e.target.checked); // 使用 setIsCover 函数来更新状态  
    formData.fm_isFunction=e.target.checked
  };  

  const beforeUpload = (file) => {  
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';  
    if (!isExcel) {  
      message.error('只能上传Excel文件（.xlsx）');  
      return false;  
    }  
    return true;  
  };  

   // 添加新行的函数  
   const addRow = () => {  
    setDataSource([  
      ...dataSource,  
      {  
        key: Date.now(), // 使用时间戳作为唯一的 key  
        inciCn: '',  
        inciUs: '',  
        percentage: '', 
        editStatus:false, 
      },  
    ]);  
  };  
  
  // 删除行的函数  
  const deleteRow = (key) => {  
    setDataSource(dataSource.filter((item) => item.key !== key));  
  };  

   // 保存编辑的函数  
   const saveEdit = (record, fieldName, value) => {  
    // 使用 immer 的 produce 来避免直接修改 state  
    // 或者使用 ... 展开操作符和 Object.assign 来创建新对象  
    const newData = [...dataSource];  
    const index = newData.findIndex((item) => item.key === record.key);  
    if (index > -1) {  
      const newItem = { ...newData[index] };  
      newItem[fieldName] = value;  
      newData.splice(index, 1, newItem);  
      setDataSource(newData);  
    }  
  };  

//select查询

const [searchResult, setSearchResult] = useState([]);  
const [visible, setVisible] = useState(false);  
const [selectedResult, setSelectedResult] = useState(null);  

const handleSearch = (values) => {  
  // 假设这里有一个异步的搜索函数，它返回搜索结果 
  values.editStatus = true 
  const fakeSearch = async () => {  
    const data={
      page:1,
      limit:999,
      search:values.inciCn,
  }
  list(data).then(res=>{
      let incis=res.data.data.page
      incis.map(item=>{
        item.name=(item.inciCn?''+item.inciCn:'') + (item.inciUs?' ,'+item.inciUs:'')
      })
      setSearchResult(incis);
      setVisible(true);  
  })
  };  
  fakeSearch()
};  

const handleSelectResult = (result) => {
  let newData = []  
  dataSource.map(i=>{
    if(i.editStatus==true){
      newData.push({key:Date.now(),inciCn:result.inciCn,inciUs:result.inciUs,percentage:i.percentage,editStatus:false})
    }else{
      newData.push(i)
    }
  })
  setDataSource(newData)
  // form.setFieldsValue({ inciStr: result.name }); // 回填表单  
  // form.setFieldsValue({lawInciSerial:result.serial})
  // form.setFieldsValue({inciCn:result.inciCn})
  // form.setFieldsValue({inciUs:result.inciUs})
  // form.setFieldsValue({ingredient:result.inciUs})
  // form.setFieldsValue({ingredientName:result.inciUs})
  setSelectedResult(result);  
  setVisible(false); // 关闭弹窗  
};  

const modalFooter = [  
  <Button key="back" onClick={() => setVisible(false)}>  
    取消  
  </Button>,  
  
]; 
  
  // 列配置  
  const columnsadd = [  
    {  
      title: 'INCI (CN or EN)',  
      dataIndex: 'inciCn',  
      key: 'inciCn',  
      render: (_, record) => (  
        <div>
        <Input  
        value={record.inciCn}  
        onChange={(e) => saveEdit(record, 'inciCn', e.target.value)} 
        style={{ width: '80%', marginRight: 8 }} // 调整Input宽度和按钮间距  
      />  
      <Button  
        type="primary" 
        size='small' 
        onClick={() => handleSearch(record)} // 绑定查询函数  
      >  
        查询  
      </Button> 
      </div> 
      ),  
    },  
    {  
      title: 'INCI US',  
      dataIndex: 'inciUs',  
      key: 'inciUs',  
      render: (_, record) => (  
        <Input  
          value={record.inciUs}  
          onChange={(e) => saveEdit(record, 'inciUs', e.target.value)}  
        />  
      ),  
    },  
    {  
      title: 'Percentage',  
      dataIndex: 'percentage',  
      key: 'percentage',  
      render: (_, record) => (  
        <Input  
          type="number"  
          value={record.percentage}  
          onChange={(e) => saveEdit(record, 'percentage', e.target.value)}  
        />  
      ),  
    },  
    {  
      title: 'Action',  
      dataIndex: 'action',  
      key: 'action',  
      render: (_, record) => (  
        <Popconfirm title="确认删除？" onConfirm={() => deleteRow(record.key)}>  
          <a>{t('delete')}</a>  
        </Popconfirm>  
      ),  
    },  
  ];  
  
  // 这里可以添加一个按钮来触发 addRow 函数  
  const handleAdd = () => {  
    addRow();  
  };  

  const handleDownload = () => {  
    // 这里可以添加处理下载操作的逻辑，比如调用下载接口  
    download("/api/Ts/exportFmCheckTemplate", {
      
    }, `Formula Screening Template.xlsx`);
  };  
  
  
  return (  
    <div>
    <FullscreenLoading showLoading={loading} loadingTip="Loading..."/> 
    <Card>
    <Modal  
        title="Search Result"  
        visible={visible}  
        onCancel={() => setVisible(false)}  
        footer={modalFooter}  
      >  
        <List  
          itemLayout="horizontal"  
          dataSource={searchResult}  
          renderItem={(item) => (  
            <List.Item  
              actions={[  
                <Button type="link" onClick={() => handleSelectResult(item)}>  
                  选择  
                </Button>,  
              ]}  
            >  
              <List.Item.Meta  
                title={<span>{item.name}</span>}  
              />  
            </List.Item>  
          )}  
        />  
      </Modal>  
    <Form form={form} onFinish={handleSubmit} >  
      <Form.Item  
        name="file"  
        label="上传文件"  
        valuePropName="fileList"  
        labelCol={{ style: { width: '120px', textAlign: 'left'  } }} // 使用内联样式替代类名
        getValueFromEvent={({ fileList }) => fileList}  
      >  
        <Upload  
          customRequest={({ file, onSuccess, onError }) => {  
            // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
            // 例如，使用axios发送POST请求上传文件  
            // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
          }}  
          beforeUpload={beforeUpload}  
          onChange={handleFileChange} 
        >  
          <Button icon={<UploadOutlined />}>{t('selectUpload')}</Button>  
          
        </Upload>  
        <Button icon={<DownloadOutlined></DownloadOutlined>} style={{marginTop:'2%'}} type="primary" onClick={handleDownload}>  
            {t('report.templateDownload')}  
          </Button>
      </Form.Item> 
      <Checkbox  
                     className="isCover"  
                     checked={fm_isCover1}  
                     onChange={handleIsCoverCheckboxChange} 
                   >  
          {t('report.ManuallyAdd')}  
      </Checkbox> 
      
      {fm_isCover1 == true &&(
        <div style={{marginTop:'2%'}}>
          <Button type='primary' size='small' onClick={handleAdd}>{t('add')}</Button>  
          <Table 
           style={{marginTop:'2%'}} 
            columns={columnsadd}  
            dataSource={dataSource}  
            rowKey="key"  
            pagination={false} // 根据你的需求添加分页  
            // 其他 Table 属性...  
          />  
        </div>
    
      )}
      <div style={{marginTop:'2%'}}></div>
      <Row justify="center" align="middle">  
        <Col>  
        <Form.Item>  
            <Button type="primary" htmlType="submit" loading={uploading}>  
            {t('report.Next')}  
            </Button>  
        </Form.Item> 
        </Col>  
    </Row>   
    
    </Form>
    </Card>
    
    </div> 
  );  
};  
  
export default FileUpload;